package ws

import (
	"fmt" // 导入 fmt 包
	"log"
)

// 接收消息模板：从指定客户端接收消息
// 实际的消息接收逻辑在 client.go 的 readPump 中处理，并广播到 Hub。
// 此函数仅作为模板，用于演示如何打印接收到的消息。
func ReceiveMessageFromClient(c *Client, message []byte) {
	if c == nil {
		fmt.Printf("Error: Cannot receive message from a nil client.\n")
		return
	}
	//对消息 message 进行简析,并返回用户 客户端消息

	msg := []byte("收到你的消息了")
	//发送消息给用户
	select {
	case c.send <- msg:
		fmt.Println("Sent message to client %p: %s\n", c, msg)
	default:
		fmt.Printf("Warning: Client send channel is full, message dropped for client %p\n", c)
	}
}

// 发送消息模板：发送消息给所有连接的客户端
func SendMessageToAllClients(h *Hub, message []byte) {
	if h == nil {
		fmt.Printf("Error: Cannot broadcast message, Hub is nil.\n")
		return
	}
	h.broadcast <- message
	fmt.Printf("Broadcasted message to all clients: %s\n", message)
}

// 发送消息模板：发送消息给指定用户
// 调用 SendMessageToUser 方法发送信息
// var Hub = ws.NewHub()
//
//	targetUserID := c.Param("userId")
//	message := []byte("我给你发消息了")
//	ws.SendMessageToUser(Hub, targetUserID, message)
func SendMessageToUser(h *Hub, userID string, message []byte) {
	if h == nil {
		fmt.Printf("Error: Cannot send message to user, Hub is nil.\n")
		return
	}
	if userID == "" {
		fmt.Printf("Error: UserID cannot be empty for SendMessageToUser.\n")
		return
	}
	h.sendToUser <- struct {
		userID  string
		message []byte
	}{userID: userID, message: message}
	fmt.Printf("Sent message to user %s: %s\n", userID, message)
}

// 关闭连接
func CloseConnection(c *Client) {
	if c == nil {
		log.Println("Error: Cannot close connection for a nil client.")
		return
	}
	log.Printf("Closing connection for client %p", c)
	close(c.send)
}

// 心跳检测 (原函数，保留以避免破坏现有结构)
func PingMessage(c *Client) {
	log.Printf("Warning: PingMessage for client %p is ambiguous. Periodic pings are handled by writePump.", c)
	// No direct ping mechanism exposed here.
}

// 打开/建立连接
func openConnection(address string) *Client {
	log.Printf("Warning: openConnection(address string) is ambiguous in this server-side context. Connections are typically established via HTTP upgrade. Returning nil.")
	return nil
}
